/**
 * Created by denn on 2017/12/12.
 */

layui.config({base: js + 'js/lay-ext/'}).define(['basis'], function (exports) {
    "use strict";

    var base = layui.basis, form = layui.mobi_form, MOD_NAME = 'DS_MOBI', mobi_upload = layui.mobi_upload;
    var user_id = 0;
    base.module = 'mobi';

    /*退出登录*/
    base.logout = function () {

        layui.data('2957297735fbf429', null);
        layui.data('cart', {key: 'cart_num', value: '0'});
        // base.sendAjax({
        //     data: {
        //         s: 'Default.Logout',
        //         root:'user/user/logout'
        //     },
        //     success: function () {
                //TODO 修改手机基础板块跳转
                $.router.loadPage('../index/login.html', true);
        //     }
        // });
    };
    base.countdown = function (endTime, serverTime, callback) {
        var that = this
            , type = typeof serverTime === 'function'
            , end = new Date(endTime).getTime()
            , now = new Date((!serverTime || type) ? new Date().getTime() : serverTime).getTime()
            , count = end - now
            , time = [
            Math.floor(count / (1000 * 60 * 60 * 24)) //天
            , Math.floor(count / (1000 * 60 * 60)) % 24 //时
            , Math.floor(count / (1000 * 60)) % 60 //分
            , Math.floor(count / 1000) % 60 //秒
        ];

        if (type) callback = serverTime;

        var timer = setTimeout(function () {
            that.countdown(endTime, now + 1000, callback);
        }, 1000);

        callback && callback(count > 0 ? time : [0, 0, 0, 0], serverTime, timer);

        if (count <= 0) clearTimeout(timer);
        return timer;
    }
    /*pickData的数据渲染*/
    base.pickerData = function (data) {
        var values = [], displayValues = [], data = typeof data === 'string' ? JSON.parse(data) : data;
        for (var k in data) {
            values.push(k);
            displayValues.push(data[k]);
        }
        return {
            textAlign: 'center',
            values: values,
            displayValues: displayValues
        }
    };

    /*下拉加载更多的渲染*/
    base.noMore = function (state) {
        return !state ? '<div class="preloader"></div>' : '<fieldset style="border: none;border-top: 1px solid #e8e8e8 ;margin: 0 20px; "><legend style="padding: 0 10px">已经到底了</legend></fieldset>'
    };
    /*下拉加载更多的绑定*/
    base.pageLoadMore = function (loading, page) {//兼容之前的版本
        var infinite = $('#' + page + ' .infinite-scroll');
        if (infinite.length > 0) {
            if (loading == 2) {
                $.detachInfiniteScroll(infinite);
                infinite.find('.infinite-scroll-preloader').html(base.noMore(true));
            } else if (loading == 0) {
                $.attachInfiniteScroll(infinite);
                infinite.find('.infinite-scroll-preloader').html(base.noMore());
            }
        }

    };
    /*成功的提示信息*/
    base.successMsg = function (d, $callback) {
        var $msg = d.msg || d || '';
        $.toast($msg);
        setTimeout(function () {
            $callback ? $callback(d.data) : '';
        }, 1500)
    };
    /*失败的提示信息*/
    base.errorMsg = function (d) {

        if (d.code == 40003) {//没有登录跳转到登录页
            //清空缓存key值
            base.logout();
        } else if (d.code == 40004) {//跳转到设置安全密码
            // $.router.loadPage('pwd_set.html', true);
        }
        var $msg = d.msg || d || '';
        $.toast($msg);
    };
    /*confirm提示信息*/
    base.confirm = function (title, $callback) {
        $.confirm(title, function () {
            $callback ? $callback() : '';
        });
    };

    /*清空参数传递*/
    base.emptyParams = function () {
        $.router.params = {};
    };


    /*swiper重复初始化*/
    base.swiper_init = function (selector, options) {
        var banner = $(selector);
        var data = $(banner).data('swiper');
        if (data) {
            if ($.isArray(data)) {
                for (var i = 0, len = data.length; i < len; i++) {
                    data[i].destroy();
                }
            } else {
                data.destroy();
            }
        }
        $(banner).data('swiper', new Swiper(selector, options));
    };

    /*根据地址ID地址信息*/
    base.getAddress = function ($province, $city, $area) {
        var data = {province: '', city: '', area: ''};
        for (var i = 0; i < cityData3.length; i++) {
            var PCAPT = cityData3[i].text;
            var PCAPV = cityData3[i].value;
            if (PCAPV == $province) {
                data.province = PCAPT;
                var PI = i;
                for (var i = 0; i < cityData3[PI].children.length; i++) {
                    var PCACT = cityData3[PI].children[i].text;
                    var PCACV = cityData3[PI].children[i].value;
                    if ($city == PCACV) {
                        data.city = PCACT;
                        var CI = i;
                        for (var i = 0; i < cityData3[PI].children[CI].children.length; i++) {
                            var PCAAT = cityData3[PI].children[CI].children[i].text;
                            var PCAAV = cityData3[PI].children[CI].children[i].value;
                            if ($area == PCAAV) {
                                data.area = PCAAT
                            }
                        }
                        break
                    }
                }
                break
            }
        }
        return data;
    };

    /*改变所有购物车的数量*/
    base.cart_num = function (num) {
        $('.cart_num').html(num);
    };

    /*刷新当前页*/
    base.click('refresh', function (d) {
        if (d.data.href) {
            $.router.loadPage(d.data.href, true, false, true);
            return;
        }
        $.router.reloadPage();
        return;
    });
    base.click('verify_code', function (d) {
        $(this).attr('src', base.base_url + '?s=Public.Verify');
        return;
    });

    base.click('logout', function () {
        base.logout();
    });

    base.click('confirm', function (d) {
        var result = d.data;
        base.confirm(result.title, function () {
            var data = $.extend({}, result);
            delete data.remote;
            base.sendButtonAjax(d.elem, data, function (data) {
                if (result.href) {
                    $.router.loadPage(result.href, $(d.elem).hasClass('no-transition'), $(d.elem).hasClass('replace'));
                } else if (result.remote) {
                    result.remote(data, d.elem);//回调
                } else {
                    $.router.back('');
                }
                $.router.backReloadTime(result['reload'] || 0);
            }, function (data) {
                if (result.errRemote) {
                    result.errRemote(data);//回调
                }
            });
        });
    });
    base.click('prompts', function (d) {
        var result = d.data;


        $.prompt(result.text, result.title, function (value) {
            result[result.name] = value;
            var data = $.extend({}, result);
            delete data.remote;
            base.sendButtonAjax(d.elem, data, function (data) {
                if (result.href) {
                    $.router.loadPage(result.href, $(d.elem).hasClass('no-transition'), $(d.elem).hasClass('replace'));
                } else if (result.remote) {
                    result.remote(data);//回调
                } else {
                    $.router.back('');

                }
                $.router.backReloadTime(result['reload'] || 0);
            }, function (data) {
                if (result.errRemote) {
                    result.errRemote(data);//回调
                }
            });
        });
    });

    /*获取会员真实姓名*/
    base.blur('username', function (d) {

        var ERROR = 'color-danger', $this = $(d.elem), info = $this.parent().parent().parent().find('.lay-info');
        info.removeClass(ERROR);
        var value = $this.val();
        info.html('');
        if (value == '' && $this.attr('lay-verify').indexOf('required') > -1) {
            /*  base.errorMsg('必填项不能为空');
              info.addClass(ERROR)*/
            return;
        }
        base.sendAjax({
            data: {s: 'Public.CheckUserField', field: 'username', value: value},
            success: function (data) {
                if (data.code == 200) {
                    info.html(data.data.true_name)
                } else {
                    info.html(data.msg);
                    $this.addClass(ERROR);
                }
            }
        });
    });
    //layui-form 表单提交后退一页并刷新页面 （登录页验证码刷新）
    form.on('submit(LoginRefreshForm)', function (d) {
        base.sendButtonAjax(d.elem, d.field, function (data) {
            $.router.backReloadTime(d.field.reload || 1);
            $.router.back('?');
        }, function (d) {
            base.errorMsg(d);
            $('#login_verify').click();
        });
        return false;
    });//提交订单后退并刷新页面
    //layui-form 表单提交后退一页并刷新页面
    form.on('submit(BackRefreshForm)', function (d) {

        if (d.field.s == "SettleUser.UserAddSub") {

            var agree = $('input[name="agree"]')[0].checked;

            if (agree === 'undefined' || agree == '' || agree == false) {

                base.errorMsg('请勾选同意协议');
                return;
            }

        }

        base.sendButtonAjax(d.elem, d.field, function (data) {
            $.router.back('?');
            $.router.backReloadTime(d.field.reload || 1);
        });
        return false;
    });//提交订单后退并刷新页面
    form.on('submit(register)', function (d) {

        var btn = $(d.elem);
        base.sendButtonAjax(d.elem, d.field, function (data) {

            if (d.field.s == 'Default.DoLogin') {
                layui.data('2957297735fbf429', {
                    key: 'id'
                    , value: data.user_id
                });
            }

            if (btn.data('href')) {
                $.router.loadPage(btn.data('href'), btn.hasClass('no-transition'), btn.hasClass('replace'));
            } else if (btn.data('remote')) {
                btn.data('remote')(data);//回调
            } else {
                $.router.back('');
            }
            $.router.backReloadTime(btn.data('reload') || 0);
        }, function (data) {

            if(data.msg == "您没有可用的收款账号"){

                btn.data('errRemote')(data);//回调
            }
            if (btn.data('errRemote')) {
                btn.data('errRemote')(data);//回调
            }
        });
    });
    form.on('submit(prompt)', function (d) {

        var btn = $(d.elem);
        $.prompt(btn.data('text'), btn.data('title'), function (value) {
            d.field[btn.data('name')] = value;
            base.sendButtonAjax(d.elem, d.field, function (data) {
                if (btn.data('href')) {
                    $.router.loadPage(btn.data('href'), btn.hasClass('no-transition'), btn.hasClass('replace'));
                } else if (btn.data('remote')) {
                    btn.data('remote')(data);//回调
                } else {
                    $.router.back('');
                }
                $.router.backReloadTime(btn.data('reload') || 0);
            }, function (data) {
                if (btn.data('errRemote')) {
                    btn.data('errRemote')(data);//回调
                }
            });
        })

    });
    /*layui-form 表单提交后后退一页*/
    form.on('submit(BackForm)', function (d) {//layui-form 的表单参数
        base.sendButtonAjax(d.elem, d.field, function (data) {
            $.router.back('?');
        });
        return false;
    });
    form.on('submit(WapRefreshForm)', function (d) {
        base.sendButtonAjax(d.elem, d.field, function (data) {
            $.router.backReloadTime(d.field.reload || 1);
            $.router.back('?');
        });
        return false;
    });

    //提交表单后退不刷新页面
    form.verify({
        username: [/[a-zA-Z0-9]{4,16}/, '会员账号必须4-16为字母或数字']
        , pass: [/(.+){6,12}$/, '密码必须6到12位'],
        require: function (value, item) {

            if (!/[\S]+/.test(value)) {
                return $(item).data('verify') || $(item).attr('placeholder') || '必填项不能为空';
            }
        },
        lsdpass:function(value, item){
            console.log(value)
            if(value != $('#passwords').val()){
                return '密码不一致';
            }

        },
        ethAddress: function (value, item) {
            if (!/^(0x|0X)?[a-f0-9A-F]{40}$/.test(value)) {
                return $(item).data('verify') || '钱包地址错误';
            }
        }
    });


    var loadFunc = {
        all: function (id, callback) {
            var data = $('#' + id).data();
            var $this = this;

            base.sendAjax({
                data: data,
                success: function (d) {
                    if (d.code == 200) {
                        $this.renderHtml(id, d.data);
                        callback ? callback(d.data) : '';
                    } else {
                        base.errorMsg(d);
                    }
                }
            });
        },
        sendAjax: function (data, callback, error) {

            base.sendAjax({
                data: data,
                success: function (d) {
                    if (d.state == '0000') {


                        callback(d.data, d.msg);
                    } else {
                        if(d.msg == '登录已过期，请重新登录'){
                            base.logout();
                        }
                        console.log(d);
                        base.errorMsg(d);
                        error ? error(d) : '';
                    }
                }
            });
        },
        rederPicker: function (id) {
            $('#' + id).find('*[lay-picker]').each(function () {
                var $this = $(this), picker = $this.attr('lay-picker'), data = $(this).data();
                switch (picker) {
                    case 'city':
                        $this.cityPicker({
                            toolbarTemplate: '<header class="bar bar-nav"><h1 class="title">选择地址</h1></header>',
                            formatValue: function (p, values, displayvalues) {
                                var par = $this.parent();
                                par.find('input[name="province"]').val(values[0]);
                                par.find('input[name="city"]').val(values[1]);
                                par.find('input[name="area"]').val(values[2]);
                                return displayvalues.join(' ');
                            }
                        });
                        break;
                    default:
                        //对应的HTML结构为 <input type="text" readonly lay-picker="" data-data="picker的数据" data-title="<?php echo T('会员级别'); ?>" value=""/> <input type="hidden" value="0" name="rank"/>
                        var picker_data = base.pickerData(data.data);
                        var v = $this.next().val();
                        for (var k in picker_data['values']) {
                            if (picker_data['values'][k] == v) {
                                $this.val(picker_data['displayValues'][k]);
                                break;
                            }
                        }
                        $this.picker({
                            toolbarTemplate: '<header class="bar bar-nav"><h1 class="title">' + data.title + '</h1></header>',
                            // rotateEffect:true,
                            cols: [picker_data],
                            formatValue: function (p, values, displayvalues) {
                                $this.next().val(values[0]);
                                return displayvalues.join(' ');
                            }
                        });
                }
            });
        },
        basis: function () {
            return base;
        },
        pageLoad: function (data, id, complete) {
            var loading = 0;

            function loadMore(data, id, complete) {

                if (data.page == 1) {
                    data.page = 1;
                    $('#' + id + ' .section').html('');
                }
                if (loading == 1){
                    base.pageLoadMore(2, id);
                    return;
                }
                loading = 1;
                base.sendAjax({
                    data: data,
                    success: function (d) {
                        if (d.state == '0000') {
                            var da = {rows:d.data};
                            // data.page = data.page++;

                            typeof complete == 'function' ? ($('#' + id + ' .section').append(complete(da))) : complete.callback(da);

                            if (parseInt(da.rows.length) < parseInt(data.count)) {
                                $('#' + id + ' .section').css('min-height', 0);
                                loading = 2;
                            } else {
                                loading = 0;
                                $('#' + id + ' .section').css('min-height', '100%');
                            }

                            base.pageLoadMore(loading, id);
                        } else {
                            console.log(1111)
                            base.errorMsg(d);
                        }
                    }
                })
            }

            loadMore(data, id, complete);
            $(document).off('infinite', '#' + id + ' .infinite-scroll').on('infinite', '#' + id + ' .infinite-scroll', function () {//监听下拉加载更多事件
                // 如果正在加载，则退出
                if(loading == 0){
                    data.page++;
                    loadMore(data, id, complete);
                }
            });
        },
        renderHtml: function (id, data, callback) {
            $('#' + id).find("*[render]").each(function () {
                var r = $(this).attr('render');
                if (typeof data[r] != 'undefined') {
                    if ($(this).is(':input')) {
                        $(this).val(data[r]);
                    } else {
                        $(this).html(data[r]);
                    }
                }

            });
            callback ? callback() : '';
        },
        upload: function (params, callback) {
            var root = params.root || '';
            delete params.root;
            params.headers = {
                'Isapp': true,
                Sign: base.url(params.data, true)
            };

            mobi_upload.render($.extend({
                done: function (d) {
                    //上传完毕回调
                    if (d.state == '0000') {
                        callback(d.data)
                    } else {
                        base.errorMsg(d);
                    }
                }
                , error: function () {
                    base.errorMsg('请求异常');
                }, url: base.base_url + root
            }, params))
        }
    };

    /*window.addEventListener('resize', function () {

        if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
            window.setTimeout(function () {
                document.activeElement.scrollIntoViewIfNeeded();
            }, 100);
        }
    });*/
    //阻止微信端的下拉显示网址
    /* document.addEventListener('touchmove', function(e) {
         e.preventDefault()
     }, false);*/

    /*增加所有picker的绑定渲染*/
    /*(function(m, ei, q, i, a, j, s) {
        m[i] = m[i] || function() {
            (m[i].a = m[i].a || []).push(arguments)
        };
        j = ei.createElement(q),
            s = ei.getElementsByTagName(q)[0];
        j.async = true;
        j.charset = 'UTF-8';
        j.src = 'https://static.meiqia.com/dist/meiqia.js?_=t';
        s.parentNode.insertBefore(j, s);
    })(window, document, 'script', '_MEIQIA');
    _MEIQIA('entId', 114837);//客服*/
    $('title').html('西谷非遗数字资产');

    function loadP(id) {

        if (!id) return;
        if(id == 'pwd_set') return;
        if (not_login.indexOf(id) === -1) {
            // console.log(id);
            var user_id = layui.data('2957297735fbf429');
            if (!user_id || !user_id['id']) {

                $.ajax({
                    type:"POST",
                    url:"http://sagoce.com/api/user/user/profile",
                    dataType:"json",
                    data:{},
                    success:function(data){
                      // console.log(111);
                        if(data.state == '0000'){
                            if(data.data.is_safepassword == '0'){
                                $.router.loadPage('pwd_set.html', true);
                            } else {
                                $.router.loadPage('../index/login.html');
                            }
                        } else {
                            $.router.loadPage('../index/login.html');
                        }
                    }
                });


                return;
            } else {
            	if(id == "order_set"){
                  $.ajax({
                    type:"POST",
                    url:"http://sagoce.com/api/user/user/profile",
                    dataType:"json",
                    data:{},
                    success:function(data){
                      console.log(111);
                        if(data.state == '0000'){
                          	if(data.data.remit_status == '1'){
                            	  $(".dis").addClass("ac")
                            }
                          
                        }
                    }
                });
                   
                }
            	console.log(2222);
            }
        } else {

            var user_id = layui.data('2957297735fbf429');
            if (user_id && user_id['id']) {

                $.router.loadPage('../index/wap.html', true, true);
                return;
            }

        }

        $('#' + id + ' .verify_code').trigger('click');
        $('#' + id + ' form').each(function () {
            var obj = [], vals = [];
            $(this).find(':input[render]').each(function () {
                obj.push($(this));
                vals.push($(this).val())
            });
            this.reset();
            for (var k  in obj) {
                obj[k].val(vals[k]);
            }
        });

        if (!$.router.params.back || base.getQueryString('reload')) {
            if (loadFunc[id]) {
                loadFunc[id](id);
            } else {

                if ($('#' + id + '_script')) {
                    eval.call(window, $('#' + id + '_script').html());
                }
                if (loadFunc[id]) {
                    loadFunc[id](id);
                } else if ($('#' + id).data('s')) {
                    loadFunc.all(id);
                }
            }
        }

    }

    var not_login = ['login', 'join', 'pwd_find','pwd_set'];

    $(document).off('pageReinit pageInit').on('pageReinit pageInit', function (e, id) {//监听页面渲染的结果
        $.modal.prototype.defaults.closePrevious = true;

        loadP(id);

    });
    $(document).on('open', '.popup', function () {//监听弹框事件，触发对应的渲染事件
        var id = $(this).attr('id');
        loadP(id);

    });


    document.body.addEventListener('touchstart', function () {
    });

    base.picker = function (filter, callback) {
        layui.onevent.call(this, MOD_NAME, 'picker(' + filter + ')', callback);
        return this;
    };

    base.refreshPicker = function ($selector, d,ds) {
        var $this = $($selector), data = $this.data();
        var filter = $this.attr('lay-filter') || '';
        var picker_data = base.pickerData(d);
        var replace = $('<input type="text" readonly lay-picker="" lay-filter="' + filter + '" data-title="' + data.title + '" value="' + picker_data.displayValues[0] + '"/>');
        $this.picker('destroy');
        $this.next().replaceWith('<input type="hidden" value="' + picker_data.values[0] + '" name="' + ($this.next().attr('name')) + '"/>');
        $this.replaceWith(replace);
        if (filter) {
            layui.event.call(replace, MOD_NAME, 'picker(' + filter + ')', {
                elem: this,
                data: {key: picker_data.values[0], value: picker_data.displayValues[0]}
            });
        }
        replace.picker({
            toolbarTemplate: '<header class="bar bar-nav"><button class="button button-link pull-right close-picker">' + $_LANG['picker_confirm'] + '</button> <h1 class="title">' + data.title + '</h1></header>',
            // rotateEffect:true,
            cols: [picker_data],
            formatValue: function (p, values, displayvalues) {
                if (filter) {
                    layui.event.call(replace, MOD_NAME, 'picker(' + filter + ')', {
                        elem: this,
                        data: {key: values[0], value: displayvalues[0]}
                    });
                }

                replace.next().val(values[0]);
                if(replace.next().next()){
                    replace.next().next().val(ds[values[0]]);
                }
                return displayvalues.join(' ');
            }
        });
    }

    $(document).on('refresh', '.pull-to-refresh-content', function (e) {
        setTimeout(function () {
            $.router.reloadPage();
        }, 1000);
    });


    $(window).off('pageLoadToast').on('pageLoadToast', function () {
        var msg = $.router.params.msg;
        base.emptyParams();
        base.errorMsg({code: 40001, msg: msg});
    });

    layui.loadPage = function (params) {/*用于扩展页面调用过程中的*/
        loadFunc = $.extend(loadFunc, params);
        layui.loadFunc = loadFunc;
    };

   /* var resize = function () {
        var width = $(window).width();
        width = width > 640 ? 640 : width;
        var font = (width / 320 * 18);
        $('html').css({'font-size': font });
    };
    //将所有html font-size 等比例放大
    $(window).on("resize",resize);
    resize()*/

    exports('page');
})
